// pages/group/group.js
import Notify from '@vant/weapp/notify/notify';

let app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userId: 0,
        lookserch: false,
        keyCodeForSearch: '',
        list: [],
        configColor: app.globalData.configColor,
        ColorMost: app.globalData.ColorMost,
        selected: '',
        chooseCarId: 0,
        pop_show: false,
        keyCode: '',
        showSearchResult: false,
        dialogMessage: '',
        searchCarId: 0,
        carNumber: '',
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
    },
    go_my() {
        wx.switchTab({
            url: '/pages/my/my',
        })
    },
    changeSearch(e) {
        //   console.log(this.data.keyCodeForSearch)
        this.setData({
            keyCodeForSearch: e.detail,
        });
    },
    // 滑动块
    onTap(event) {
        let instance = this.selectComponent("#" + this.data.selected + "");
        if (instance != null) { instance.close(); }
    },
    onCloseSwipe(event) {
        // const { position, instance } = event.detail;
        event.detail.instance.close();

        // const { position, instance } = event.detail;
        // switch (position) {
        // case 'left':
        // case 'cell':
        //     instance.close();
        //     break;
        // case 'right':
        //     instance.close();
        //     break;
        // }
    },
    onOpenSwipe(event) {
        this.setData({
            selected: event.currentTarget.id
        })
    },
    onOpenSwipe2(event) {
        // console.log(this.selectComponent("#"+ event.currentTarget.dataset.zujianid+""))
        // this.selectComponent("#"+ event.currentTarget.dataset.zujianid+"").open("right")
        this.selectComponent("#" + event.currentTarget.dataset.zujianid + "").open("right")
        this.setData({
            selected: event.currentTarget.dataset.zujianid
        })
    },
    onClose() {
        this.setData({
            pop_show: false
        })
    },
    chooseCar(event) {
        wx.request({
            url: app.globalData.url + '/updateUserCarChoose',
            method: 'GET',
            data: {
                id: event.currentTarget.dataset.chooseid,
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                let re = res.data
                if (re.flag) {
                    let userInfo = wx.getStorageSync('userInfo');
                    userInfo.number = event.currentTarget.dataset.number
                    // console.log(userInfo) 
                    wx.setStorageSync('userInfo', userInfo);
                    wx.switchTab({
                        url: '/pages/oil/oil',
                    })
                } else {
                    wx.showToast({
                        title: '选择失败，请重试',
                        icon: 'none'
                    })
                }
            }
        })

    },

    // 新增或修改车辆
    submitForm(e) {
        let carNumber = e.detail.value.carNumber
        let keyCode = e.detail.value.keyCode
        wx.request({
            url: app.globalData.url + '/addorUpdateCar',
            header: {
                'content-type': 'application/json'
            },
            method: 'POST',
            data: {
                id: this.data.chooseCarId,
                number: carNumber,
                keycode: keyCode,
                userId: wx.getStorageSync('userInfo').id
            },
            success: (res) => {
                let responseData = res.data
                if (responseData.flag) {
                    wx.showToast({
                        title: '操作成功',
                        icon: 'none'
                    })
                    this.setData({
                        carNumber: '',
                        keyCode: '',
                        chooseCarId: 0,
                        pop_show: false
                    })
                    // 如果是创建的第一辆车,加进userInfo
                    if (this.data.list.length < 1) {
                        let userInfo = wx.getStorageSync('userInfo');
                        userInfo.number = carNumber
                        wx.setStorageSync('userInfo', userInfo);
                        console.log(wx.setStorageSync('userInfo', userInfo))
                    }
                    this.onSearch()
                } else {
                    wx.showToast({
                        title: '操作失败:' + responseData.message,
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log("失败", err);
            },
            complete: (com) => {
                wx.hideLoading()
            }
        })

    },

    // 回显编辑车辆
    edit(e) {
        if (e.currentTarget.dataset.userid != wx.getStorageSync('userInfo').id) {
            wx.showToast({
                title: '禁止编辑他人车辆',
                icon: 'none'
            })
            return
        }
        this.setData({
            pop_show: true,
            chooseCarId: e.currentTarget.dataset.id,
            carNumber: e.currentTarget.dataset.number,
            keyCode: e.currentTarget.dataset.keycode
        })
    },

    // 删除or退出车辆
    delExitCar(e) {
        let title = ''
        let content = ''
        if (e.currentTarget.dataset.userid == wx.getStorageSync('userInfo').id) {
            title = '删除车辆'
            content = '警告:删除后加油记录不可恢复!'
        } else {
            title = '退出车辆'
            content = '确认退出车辆'
        }

        wx.showModal({
            title: title,
            content: content,
            complete: (res) => {
                if (res.cancel) {
                }
                if (res.confirm) {
                    wx.request({
                        url: app.globalData.url + '/delExitCar',
                        header: {
                            'content-type': 'application/json'
                        },
                        method: 'POST',
                        data: {
                            id: e.currentTarget.dataset.delid,
                            userId: wx.getStorageSync('userInfo').id
                        },
                        success: (res) => {
                            let re = res.data
                            if (re.flag) {
                                this.onSearch()
                            } else {
                                wx.showToast({
                                    title: title + '失败:' + re.message,
                                    icon: 'none'
                                })
                            }
                        },
                        fail: (err) => {
                            console.log("失败", err);
                        },
                        complete: (com) => {
                            wx.hideLoading()
                        }
                    })
                }
            }
        })
    },

    add_car() {
        this.setData({
            groupId: 0,
            groupName: '',
            keyCode: '',
            pop_show: true
        })
    },

    // 加入车辆
    jiaru() {
        let that = this
        wx.request({
            url: app.globalData.url + '/addOtherCar',
            method: 'GET',
            data: {
                id: that.data.searchCarId,
                userId: wx.getStorageSync('userInfo').id
            },
            success: (res => {
                let responseData = res.data
                if (!responseData.flag) {
                    Notify({
                        message: '\n  加入失败: ' + responseData.message + ' !!! \n',
                        duration: 2000,
                        selector: '#custom-selector',
                    });
                }
            }),
            fail: (err) => {
                wx.showToast({
                    title: '请求失败,请稍后重试',
                    icon: 'none'
                })
            },
            complete: () => {
                this.onSearch()
            }
        })
        this.setData({
            showSearchResult: false,
            dialogMessage: '',
            keyCodeForSearch: '',
            searchCarId: 0
        })
    },

    closeDia() {
        this.setData({
            showSearchResult: false,
            dialogMessage: '',
            keyCodeForSearch: ''
        })
    },

    // 搜索车辆
    onSearch() {
        let that = this
        wx.showLoading({
            title: '搜索中',
        })
        wx.request({
            url: app.globalData.url + '/getCarByUser',
            method: 'GET',
            data: {
                keycode: that.data.keyCodeForSearch,
                userId: wx.getStorageSync('userInfo').id
            },
            success: (res => {
                // console.log(res.data)
                let responseData = res.data
                if (responseData.flag) {
                    if (that.data.keyCodeForSearch.length > 0) {
                        // 通过秘钥搜索
                        if (responseData.data.length == 1) {
                            this.setData({
                                showSearchResult: true,
                                dialogMessage: '创建人: ' + responseData.data[0].userName + '\n 车牌号: ' + responseData.data[0].number,
                                searchCarId: responseData.data[0].id
                            })
                        } else {
                            Notify({
                                message: '\n  车辆不存在!!! \n',
                                duration: 2000,
                                selector: '#custom-selector',
                            });
                            this.setData({
                                showSearchResult: false,
                                dialogMessage: '',
                                keyCodeForSearch: '',
                                searchCarId: 0
                            })
                        }
                    } else {
                        // console.log(responseData.data)
                        if (responseData.data.length < 1) {
                            let userInfo = wx.getStorageSync('userInfo');
                            userInfo.number = ''
                            wx.setStorageSync('userInfo', userInfo);
                        }
                        this.setData({
                            list: responseData.data
                        })
                    }
                }
            }),
            fail: (err) => {
                wx.showToast({
                    title: '请求失败,请稍后重试',
                    icon: 'none'
                })
            },
            complete: (c => {
                wx.hideLoading()
            })
        })
    },

    /**
      * 生命周期函数--监听页面显示
      */
    onShow() {
        if (wx.getStorageSync('configColor') !== this.data.configColor
            || wx.getStorageSync('ColorMost') !== this.data.ColorMost) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
            this.setData({ ColorMost: wx.getStorageSync('ColorMost') });
        }
        this.setData({
            // chooseGroupId: wx.getStorageSync('userInfo').groupVO.id,
            userId: wx.getStorageSync('userInfo').id
        })
        this.onSearch()
    },
    /**
       * 生命周期函数--监听页面加载
       */
    onLoad(options) {
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})